package com.xudow.app.ui.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.activeshare.edu.ucenter.common.messages.Sites;
import com.activeshare.edu.ucenter.models.course.CourseWithOtherInfo;
import com.activeshare.edu.ucenter.models.order.AgencyOrderDetail;
import com.activeshare.edu.ucenter.models.order.AgencyOrderItemDetail;
import com.xudow.app.Config;
import com.xudow.app.R;
import com.xudow.app.XApplication;
import com.xudow.app.model.Student;
import com.xudow.app.ui.LoginActivity;
import com.xudow.app.ui.OrderDetailActivity;
import com.xudow.app.ui.PayActivity;
import com.xudow.app.ui.SiteCardActivity;
import com.xudow.app.ui.SitesActivity;
import com.xudow.app.ui.task.OrderDetailTask;
import com.xudow.app.ui.user.DataUpdateListener;
import com.xudow.app.ui.user.OrderListFragment;
import com.xudow.app.ui.user.OrdersActivity;
import com.xudow.app.util.ImageUtils;

import org.w3c.dom.Text;

import java.util.HashMap;
import java.util.List;

/**
 * 作者：zhouXJ on 2016/5/10 18:46
 */
public class OrderListAdapter extends BaseExpandableListAdapter {
    private Context context;
    private List<AgencyOrderDetail> data;
    private DataUpdateListener dataUpdateListener;
    XApplication Myapp;
    public OrderListAdapter(Context context,List<AgencyOrderDetail> data){
        this.context=context;
        this.data=data;
        Myapp=(XApplication)(context.getApplicationContext());
    }
    public void setDataUpdateListener(DataUpdateListener dataUpdateListener){
        this.dataUpdateListener=dataUpdateListener;
    }
    @Override
    public int getGroupCount() {
        if (null==data)
            return 0;
        else
            return data.size()+1;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        if (groupPosition<data.size())
            return data.get(groupPosition).getItems().size();
        else
            return 0;
    }

    @Override
    public Object getGroup(int groupPosition) {
        if (groupPosition<data.size())
            return data.get(groupPosition);
        else
            return null;
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        if (groupPosition<data.size())
            return data.get(groupPosition).getItems().get(childPosition);
        else
            return null;
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View v, ViewGroup parent) {
        GroupHolder holder;
        if (null==v){
            holder=new GroupHolder();
            v=View.inflate(context, R.layout.orderlist_group_item,null);
            holder.coursecount_last=(TextView)v.findViewById(R.id.course_count_tv);
            holder.reduce_price=(TextView)v.findViewById(R.id.idscount_tv);
            holder.totalprice_last=(TextView)v.findViewById(R.id.total_price_tv);
            holder.lastlayout=(LinearLayout)v.findViewById(R.id.last_groupend_ly);
            holder.cancle_last=(TextView)v.findViewById(R.id.cancel_tv);
            holder.pay_last=(TextView)v.findViewById(R.id.pay_tv);
            holder.unpaylayout_last=(RelativeLayout)v.findViewById(R.id.unpayed_layout);
            holder.school_ico=(ImageView)v.findViewById(R.id.school_img);
            holder.school_name=(TextView)v.findViewById(R.id.name);
            holder.order_status=(TextView)v.findViewById(R.id.order_state);
            holder.courrentgroup=(RelativeLayout)v.findViewById(R.id.courrent_order_layout);
            v.setTag(holder);
        }else
            holder=(GroupHolder) v.getTag();

            if (groupPosition==0){//第一个隐藏lastlayout
                holder.lastlayout.setVisibility(View.GONE);
                holder.courrentgroup.setVisibility(View.VISIBLE);
            }else {//不是第一个就显示
                final AgencyOrderDetail lastorder=data.get(groupPosition-1);
                holder.lastlayout.setVisibility(View.VISIBLE);
                if (data.get(groupPosition-1).getStatus()==0){//上一个订单的 支付bnt
                    holder.unpaylayout_last.setVisibility(View.VISIBLE);
                    //TODO 支付、取消订单 监听
                    holder.cancle_last.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //取消该订单
                            android.app.AlertDialog.Builder dialogBuilder = new android.app.AlertDialog.Builder(context);
                            dialogBuilder.create();

                            LayoutInflater inflater = LayoutInflater.from(context);
                            View view = inflater.inflate(R.layout.layout_dingdan, null);
                            dialogBuilder.setView(view);
                            android.app.AlertDialog alertDialog=dialogBuilder.show();
                            Button bt_ok=(Button)view.findViewById(R.id.bt_ok);
                            Button bt_no=(Button)view.findViewById(R.id.bt_no);

                            bt_ok.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    alertDialog.dismiss();
//                                    Myapp.makeToast("取消订单");
                                    dataUpdateListener.onDelete(lastorder);

                                }
                            });
                            bt_no.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                    alertDialog.dismiss();
                                }
                            });
                        }
                    });
                    holder.pay_last.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //支付该订单
                            Myapp.makeToast("支付订单");
                            dataUpdateListener.onPay(lastorder);

                        }
                    });
                }else
                    holder.unpaylayout_last.setVisibility(View.GONE);
                holder.coursecount_last.setText("共"+lastorder.getItems().size()+"门课程");
                holder.totalprice_last.setText("¥"+lastorder.getTotalPrice()+"0");
            }

        if (groupPosition>=data.size()) {
            holder.courrentgroup.setVisibility(View.GONE);
            return v;
        }
        AgencyOrderDetail order=data.get(groupPosition);
        if (null!=order.getItems()&&order.getItems().size()>0) {
            CourseWithOtherInfo course = order.getItems().get(0).getCourse();
            if (null != course) {
                if (null != course.getAgencyName() && !"null".equals(course.getAgencyName()))
                    holder.school_name.setText(course.getAgencyName() + "(" + course.getSchoolName() + ")");
                else
                    holder.school_name.setText(course.getTeacher() + "(" + course.getSchoolName() + ")");
                if (order.getStatus() == 0) {
                    holder.order_status.setText("待付款");
                } else if (order.getStatus() == 1) {
                    holder.order_status.setText("已支付");
                } else if (order.getStatus() == OrdersActivity.ORDER_STATUS_DELETED) {
                    holder.order_status.setText("已删除");
                } else if (order.getStatus() == OrdersActivity.ORDER_STATUS_EXPIRED) {
                    holder.order_status.setText("已过期");
                } else
                    holder.order_status.setText("未知");
            }
        }
        return v;
    }

    @Override
    public View getChildView( final int groupPosition, final int childPosition, boolean isLastChild, View v, ViewGroup parent) {
        if (groupPosition>=data.size())
            return null;
        boolean course_wrong_state=false;//课程状态标记（正常为false 反之为true）
        ChildHolder holder;
        if (null==v){

            holder=new ChildHolder();
            v=View.inflate(context,R.layout.orderlist_child_item,null);
            holder.course_ico=(ImageView)v.findViewById(R.id.cource_img);
            holder.course_name=(TextView)v.findViewById(R.id.courceName_tv);
            holder.actul_price=(TextView)v.findViewById(R.id.actual_price_tv);
            holder.price=(TextView)v.findViewById(R.id.price_tv);
            holder.course_type=(TextView)v.findViewById(R.id.courceType_tv);
            holder.student_name=(TextView)v.findViewById(R.id.studentName_tv);
            holder.course_card=(TextView)v.findViewById(R.id.class_card_tv);
            holder.select_sit=(TextView)v.findViewById(R.id.select_sit_tv);
            holder.paylayout=(RelativeLayout)v.findViewById(R.id.payed_layout);
            holder.courselayout=(RelativeLayout)v.findViewById(R.id.course_layout);
            v.setTag(holder);
        }else
            holder=(ChildHolder) v.getTag();
        final AgencyOrderItemDetail item=data.get(groupPosition).getItems().get(childPosition);
            final CourseWithOtherInfo course=item.getCourse();
            if (null!=item&&null!=course) {
                Student student = item.getStudent();
                holder.course_name.setText(course.getName());
                holder.actul_price.setText("¥"+course.getActualPrice() + "0");
                holder.price.setText("¥"+course.getCoursePrice() + "0");
                holder.price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                //加载课程图片
                String imageUrl = String.format(Config.IMAGE_LOAD_URL_PARAMS, course.getThumbnail());
                ImageUtils.loadImage(context, holder.course_ico, imageUrl, R.mipmap.def_course_ico);

                if (course.getType() == 1) {
                    holder.course_type.setText("一对一");
                } else if (course.getType() == 2)
                    holder.course_type.setText("辅导班");
                if (null != student)
                    holder.student_name.setText(getString(student.getName()));

                if (data.get(groupPosition).getStatus() == OrdersActivity.ORDER_STATUS_PAID) {
                    holder.paylayout.setVisibility(View.VISIBLE);
                    holder.course_card.setVisibility(View.VISIBLE);
                    Sites s = item.getRoomSite();

                    if (null != s)
                        holder.select_sit.setText((s.getSitecolumn() + 1) + "-" + (s.getSiterow() + 1));
                    else
                        holder.select_sit.setText("请选座");
                    if (null != item.getChooseSiteNo() && item.getChooseSiteNo() == 1) {
                        String sit = "";
                        int statu = item.getStatus();
                        if (1 == statu)
                            sit = "部分退费";
                        else if (2 == statu)
                            sit = "全部退费";
                        else if (3 == statu)
                            sit = "部分转期";
                        else if (4 == statu)
                            sit = "全部转期";
                        else
                            sit = "未知";
                        holder.select_sit.setText(sit);
                        holder.select_sit.setClickable(false);
                        course_wrong_state = true;
                        holder.course_card.setVisibility(View.GONE);

                    }
                    //TODO 听课证、选座监听
                    holder.course_card.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            Intent intent = new Intent(context, SiteCardActivity.class);
                            intent.putExtra("orderItemId", item.getId());
                            context.startActivity(intent);

                        }
                    });
                    if (!course_wrong_state) {//课程状态为wrong时不设置监听
                        holder.select_sit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Log.e("选座 ", "courseId:" + item.getCourseId() + "orderItemId:" + item.getId());

                                Intent intent = new Intent(context, SitesActivity.class);
                                intent.putExtra("courseId", item.getCourseId() + "");
                                intent.putExtra("orderItemId", item.getId() + "");
                                context.startActivity(intent);

                            }
                        });
                    }

                } else {
                    holder.paylayout.setVisibility(View.GONE);
                }
            }

        holder.courselayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AgencyOrderDetail order = data.get(groupPosition);

                //课程有个status的状态，如果是 COURSE_STATUS_INVALID = 0 则表示无效了
                //当前没有购物车，一个订单不存在多个商品，取第一个即可t
                if (0 == order.getItems().get(childPosition).getCourse().getStatus()) {
                    String msg = context.getString(R.string.course_invalid);
                    Myapp.makeToast(msg);
                    return ;
                }

                //已支付订单点击后跳转至订单详情，未支付点击后跳去“订单详情”页面
                Intent intent = new Intent(context.getApplicationContext(), OrderDetailActivity.class);
                intent.putExtra("orderId", ""+order.getId());
                context.startActivity(intent);
            }
        });
        return v;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }
    class GroupHolder{
        TextView coursecount_last;
        TextView totalprice_last;
        LinearLayout lastlayout;
        TextView cancle_last;
        TextView pay_last;
        RelativeLayout unpaylayout_last;
        TextView reduce_price;
        ImageView school_ico;
        TextView school_name;
        TextView order_status;
        RelativeLayout courrentgroup;

    }

    class ChildHolder{
        ImageView course_ico;
        TextView course_name;
        TextView actul_price;
        TextView price;
        TextView course_type;
        TextView student_name;
        TextView course_card;
        TextView select_sit;
        RelativeLayout paylayout;
        RelativeLayout courselayout;
    }




    private String getString(String obj){
        return (obj==null||"null".equals(obj))? "":obj;
    }
}
